package com.exercises;


class Exercise42 {
    public static void main(String[] args) {
        System.out.println(new Exercise42().trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}));
    }


    public int trap(int[] height) {
        int area = 0;
        for (int i = 0; i < height.length; ) {
            if (height[i] != 0) {
                int l = i + 1;
                for (int j = i + 1; j < height.length; j++) {
                    if (height[j] >= height[i]) {
                        l = j;
                        break;
                    }
                    if (height[j] >= height[l]) {
                        l = j;
                    }
                }
                if (l - i >= 2) {
                    for (int j = i + 1; j < l; j++) {
                        area += Math.min(height[i], height[l]) - height[j];
                    }
                }
                i = l;
            } else {
                i++;
            }
        }
        return area;
    }
}
